package pl.edu.agh.ssm.monitor.listeners;

import java.util.List;

import jlibrtp.RtpPkt;
import pl.edu.agh.ssm.monitor.data.RTPPacket;
import pl.edu.agh.ssm.monitor.data.SessionConnection;
import pl.edu.agh.ssm.monitor.data.Packet;
import pl.edu.agh.ssm.monitor.data.Session;
import pl.edu.agh.ssm.monitor.data.SessionMedia;
import pl.edu.agh.ssm.monitor.data.SessionNode;

/**
 * This object listen and recognize data passed by rtp protocol
 * it adds informations about media type, rtp packet sequence number,
 * timestamp etc, all informations needed by this listener
 * must be setup firstly (all participants and connections between them must be
 * added before - @see {@link RTCPDataListener})
 * @author Tomasz Jadczyk
 *
 */
public class RTPDataListener implements PacketListener {

	@SuppressWarnings("unused")
	private PacketListener sessionListener = null;
	private Session session = null;
	private int priority;
	private MediaTypeInfoProvider provider;
	
	
	public RTPDataListener(PacketListener sessionListener, Session session) {
		this.sessionListener = sessionListener;
		this.session = session;
	}
	
	

	public RTPDataListener(Session session) {
		this.session = session;
	}

	@Override
	public void processPacket(Packet packet) {
		RtpPkt rtpPkt = new RtpPkt(packet.getData(), packet.getData().length);
		SessionNode sender = session.getNode(rtpPkt.getSsrc());
		if(sender != null) {
			List<SessionConnection> connections = session.getSpecifiedConnection
								(sender, packet.getDestAddress(), packet.getDestPort());
			for(SessionConnection conn : connections) {
				//set last packet info
				conn.setLastRtpPacket(new RTPPacket(rtpPkt.getSeqNumber(),
						rtpPkt.getTimeStamp()));
				
				SessionMedia mediaInfo = provider.getMediaTypeInfo(rtpPkt.getPayloadType());
				SessionMedia oldMedia = conn.getMediaDesc();
				if(oldMedia == null || oldMedia != mediaInfo) {
					conn.setMediaDesc(mediaInfo);
					session.updateConnection(conn);
				}
			}
		} 
	}

	@Override
	public void setPriority(int priority) {
		this.priority = priority;
	}
	
	@Override
	public int getPriority() {
		return priority;
	}
	
	public void setMediaTypeInfoProvider(MediaTypeInfoProvider provider) {
		this.provider = provider;
	}

}
